import xml.etree.ElementTree as ET

# 读文件
tree = ET.parse("file/my.xml")
print(tree)
# 根节点
root_ele = tree.getroot()
print(root_ele)

# 遍历节点数据
for ele in root_ele:
    print(ele)
    attr = ele.attrib  # 获取属性值
    if attr['name'] == 'china':
        for e in ele:
            print(e.tag, '---------', e.text)
print("-------------------")
# 全文搜索
# 1. 全文搜索指定名的子标签(包括所有的country标签)
cs = root_ele.iter('country')
for c in cs:
    print(c)
print('__________')
# 2. 非全文查找满足条件的第一个子标签,不能跨标签取子标签
print(root_ele.find('country').attrib)
print('----------')
# 3. 非全文查找满足条件的所有子标签
print(root_ele.findall("country"))

# 修改
print("-------------")
# 遍历节点数据
for ele in root_ele:
    attr = ele.attrib  # 获取属性值
    if attr['name'] == 'china':
        for e in ele:
            if e.tag == 'year':
                print(e.text)
                e.text = "1999"  # 这儿的修改只是写到内存中,不会更新到文件里面，需要调用下面的tree.write方法才能把内存的数据写入到文件中
# 将内存的数据重新写入文件
tree.write('file/my.xml')

# 添加内容
"""
my_ele=ET.Element('myEle')
my_ele.text='new_ele'
my_ele.attrib={'name':'my_ele'}
root.append(my_ele)
"""
my_ele = ET.Element('country')
my_ele.text = '俄罗斯'
my_ele.attrib = {'name': 'russia'}
root_ele.append(my_ele)
tree.write('file/my.xml')
